﻿using System.Web.Mvc;
using System;
using TNPTN.Services;
using TNPTN.Utility;

namespace TNPTN.Controllers
{
    /// <summary>
    /// Download Controller
    /// Author: jabraok
    /// </summary>
    public class DownloadController : BaseController
    {
        #region Constant
        private const string FILE_DOWNLOAD = "XalihAkharCam.msi";
        #endregion

        #region Common
        private TDownloadService tDownloadService;

        /// <summary>
        /// Contructor
        /// </summary>
        /// <param name="tDownloadService">TDownloadService</param>
        public DownloadController(TDownloadService tDownloadService)
        {
            this.tDownloadService = tDownloadService;
        }
        #endregion

        #region Actions

        /// <summary>
        /// Index
        /// </summary>
        /// <returns>ActionResult</returns>
        public ActionResult Index()
        {
            //Insert download
            DB.TDownload model = this.GetInsertModel();
            this.InsertData(model);

            //Download file
            this.DownloadFile(FILE_DOWNLOAD);

            return View();
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Insert data
        /// </summary>
        /// <param name="model">TDownload</param>
        private void InsertData(DB.TDownload model)
        {
            try
            {
                this.tDownloadService.Insert(model);
                this.tDownloadService.Context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Utility.Log.WriteLog(ex);
            }
        }

        /// <summary>
        /// Get Insert Model
        /// </summary>
        /// <returns>TDownload</returns>
        private DB.TDownload GetInsertModel()
        {
            DB.TDownload ret = new DB.TDownload();
            ret.IPAdress = Utility.Common.getIPAddress(this.Request);
            ret.DownloadDate = DateTime.Now;

            return ret;
        }

        #endregion
    }
}
